package Grantsfire::Controller::Test;

use strict;
use warnings;
use base 'Catalyst::Controller';

use Grantsfire::Geocoder;

sub geocode : Local {
	my ($self, $c) = @_;
	
    return unless $c->debug;

    # grab all rows that have geocoding info
    my @geocode_fields = qw/adr_post_office_box adr_extended_address adr_street_address 
      adr_locality adr_region adr_postal_code adr_country_name/;

    my @entries = $c->model('GF::Entry')->all;
    my @vcards = grep { $_ } map { $_->grant_vcard } @entries;
    $c->stash->{cards} = [];

    my $geo_card_valid_count = 0; # how many cards with geo info can be geocoded
    my @geo_cards; # cards we are doing geo lookup on

    foreach my $card (@vcards) {
        no strict 'refs';
        my $field_count = grep { $card->$_ } @geocode_fields;
        next unless $field_count;

        push @geo_cards, $card;
    }

    # do lookups
    warn "Looking up " . (scalar @geo_cards) . " vcards\n";
    my $geo_lookups = Grantsfire::Geocoder->geocode_vcards($c, @geo_cards);

    foreach my $card (@geo_cards) {
        my $field_count = grep { $card->$_ } @geocode_fields;

        $geo_card_valid_count++ if $geo_lookups->{$card->id};

        push @{$c->stash->{cards}}, {
            card => $card,
            count => $field_count,
            geo => $geo_lookups->{$card->id},
            loc => Grantsfire::Geocoder->loc_string($card),
        };
    }

    $c->stash->{geo_card_count} = (scalar @geo_cards);
    $c->stash->{vcard_count} = (scalar @vcards);
    $c->stash->{geo_card_valid_count} = $geo_card_valid_count;
    $c->stash->{addr_fields} = [Grantsfire::Geocoder->addr_fields];
	$c->stash->{template} = 'test_geocode.tt';
}

1;
